package com.dingtalk.yuanhua_spring_project.task;

import com.dingtalk.yuanhua_spring_project.pojo.Employee;
import com.dingtalk.yuanhua_spring_project.pojo.Instance;
import com.dingtalk.yuanhua_spring_project.repository.EmployeeRepository;
import com.dingtalk.yuanhua_spring_project.repository.InstanceRepository;
import com.dingtalk.yuanhua_spring_project.service.impl.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ChuZiTaskDaily {
    @Autowired
    private DingTalkYiDaimpl dingTalkYiDaimpl;
    @Autowired
    private DingTalkStorageimpl dingTalkStorageimpl;
    @Autowired
    private DingTalkAccessimpl dingTalkAccessimpl;
    @Autowired
    private DingTalkDingPanimpl dingTalkDingPanimpl;
    @Autowired
    private DingTalkYiDa1_0impl dingTalkYiDa1_0impl;
    @Autowired
    private InstanceRepository instanceRepository;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Value("${app_key}")
    private String app_key;
    @Value("${app_secret}")
    private String app_secret;
    @Value("${app_agentid}")
    private String app_agentid;
    @Value("${app_id}")
    private String app_id;
    @Value("${union_id}")
    private String union_id;
    @Value("${app_type}")
    private String app_type;
    @Value("${system_token}")
    private String system_token;
    @Value("${user_id}")
    private String user_id;
    @Value("${space_id}")
    private String space_id;
    @Value("${chuzi_zhengming_name}")
    private String chuzi_zhengming_name;
    @Value("${chuzi_zhengming_xiangmu_name}")
    private String chuzi_zhengming_xiangmu_name;
    @Value("${chuzi_zhengming_fileattach}")
    private String chuzi_zhengming_fileattach;
    @Value("${chuzi_zhengming_jijin_name}")
    private String chuzi_zhengming_jijin_name;
    @Value("${chuzi_zhengming_xiangmu_jiancheng_name}")
    private String chuzi_zhengming_xiangmu_jiancheng_name;
    @Value("${chuzi_zhengming_form_id}")
    private String chuzi_zhengming_form_id;

    private static final Logger logger = LoggerFactory.getLogger(ChuZiTaskDaily.class);

//    @Scheduled(cron = "0 0 8,22 * * ?") // 早上8点和晚上10点执行
    @Scheduled(cron = "0 0 8,22 * * ?")
    public void executeDailyTask() {
        try {
            logger.info("开始执行 出资证明-自动化任务");
            //1. 自动化任务 ， 2. 其他的表单信息， 3.添加权限 ， 4.表单和数据库进行联动，没有的再去查
            String accessToken = dingTalkAccessimpl.getAccessToken();
            logger.info("出资证明-获取到 Access Token: {}", accessToken);
            //获取所有文件夹信息
            Map<String, Map<String, String>> folderList = dingTalkStorageimpl.getFolderList(accessToken, space_id);

            List<String> instanceIdList = dingTalkYiDaimpl.getInstanceIdList(accessToken, this.app_type, this.chuzi_zhengming_form_id, this.user_id, this.system_token);
            // 获取数据库中已存在的 instanceId 列表
            List<String> existingInstanceIds = instanceRepository.findAllInstanceIds();

            for (String instanceId : instanceIdList) {
                try {
                    // 如果 instanceId 已经存在，跳过当前循环
                    if (existingInstanceIds.contains(instanceId)) {
                        continue;
                    }
                    //项目名称根据表单及附件ID来确认
                    Map<String, ?> instance = dingTalkYiDaimpl.getInstance(accessToken, instanceId);
                    logger.info("出资证明-当前 InstanceId : {}", instanceId);
                    String modifiedTimeGMT = (String) instance.get("modifiedTime");
                    String modifiedTime = modifiedTimeGMT.substring(0, 10); // 提取前10个字符，即 "yyyy-MM-dd"
                    //判断如果不是null，流程继续，否则跳过
                    if (instance == null){
                        continue;
                    }
                    String jsonString = (String) instance.get(this.chuzi_zhengming_fileattach);
                    if (jsonString == null) {
                        continue;
                    }
                    String jijin_name_component = chuzi_zhengming_jijin_name;
                    String jijin_name = (String) instance.get(chuzi_zhengming_jijin_name);
                    if (jijin_name_component != null && jijin_name_component.startsWith("association")) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        try {
                            List<Map<String, Object>> formList = objectMapper.readValue(jijin_name_component, new TypeReference<List<Map<String, Object>>>() {});
                            for (Map<String, Object> form : formList) {
                                String title = (String) form.get("title");
                                if (title != null) {
                                    jijin_name = title; // 使用提取的 title 作为 jijin_name
                                    break; // 假设只需要第一个 title
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    logger.info("出资证明-当前基金文件夹名称 : {}", jijin_name);
                    String xiangmu_name = (String) instance.get(chuzi_zhengming_xiangmu_name);
                    System.out.println(xiangmu_name);
                    logger.info("出资证明-当前项目文件夹名称 : {}", xiangmu_name);
                    String jiancheng_name = (String) instance.get(chuzi_zhengming_xiangmu_jiancheng_name);
                    logger.info("出资证明-当前项目简称文件夹名称 : {}", jiancheng_name);
                    String foldername = jiancheng_name + "-" + chuzi_zhengming_name;
                    logger.info("出资证明-当前文件夹名称 : {}", foldername);
                    //如果在folderList中找不到jijin_name，就在parentid:0创建文件夹，文件夹名称为jijin_name，重新获取所有文件夹信息
                    if (!folderList.containsKey("/" + jijin_name)) {
                        dingTalkStorageimpl.addFolder(jijin_name, space_id, "0", accessToken);
                        folderList = dingTalkStorageimpl.getFolderList(accessToken, space_id);
                    }
                    String jijinFolderId = folderList.get("/" + jijin_name).get("id");
                    if(!folderList.containsKey("/" + jijin_name + "/" + xiangmu_name)){
                        dingTalkStorageimpl.addFolder(xiangmu_name, space_id, jijinFolderId, accessToken);
                        folderList = dingTalkStorageimpl.getFolderList(accessToken, space_id);
                    }
                    String xiangmuFolderId = folderList.get("/" + jijin_name + "/" + xiangmu_name).get("id");
                    if (!folderList.containsKey("/" + jijin_name + "/" + xiangmu_name + "/" + foldername)) {
                        //防止有重名项目简称，所以校验path路径
                        dingTalkStorageimpl.addFolder(foldername, space_id, xiangmuFolderId, accessToken);
                        folderList = dingTalkStorageimpl.getFolderList(accessToken, space_id);
                    }
                    String FileSaveFolderId = folderList.get("/" + jijin_name + "/" + xiangmu_name + "/" + foldername).get("uuid");

                    // 找到所有以 employeeField ，根据表单来找出所有的项目成员
                    List<ArrayList<?>> employeeList = instance.entrySet().stream()
                            .filter(entry -> entry.getKey().startsWith("employeeField") && entry.getKey().endsWith("id"))
                            .map(Map.Entry::getValue)
                            .filter(value -> value instanceof ArrayList)
                            .map(value -> (ArrayList<?>) value)
                            .collect(Collectors.toList());
                    // 拆分 employeeList 中的值到 new_employeeList
                    List<Object> new_employeeList = employeeList.stream()
                            .flatMap(ArrayList::stream) // 将每个 ArrayList 展开成一个流
                            .collect(Collectors.toList());

                    // 去重
                    new_employeeList = new_employeeList.stream()
                            .distinct() // 去重
                            .collect(Collectors.toList());
                    System.out.println(new_employeeList);
                    // 使用Jackson解析JSON字符串
                    // 如果jsonString为空，则跳过
                    if (jsonString == null || jsonString.isEmpty()) {
                        continue;
                    }
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<Map<String, Object>> fileList = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>() {});

                    // 提取downloadUrl
                    List<String> downloadUrls = fileList.stream()
                            .map(file -> (String) file.get("downloadUrl"))
                            .collect(Collectors.toList());
                    List<String> dowloadFileName = fileList.stream()
                            .map(file -> (String) file.get("name"))
                            .collect(Collectors.toList());
                    //下载并上传文件
                    for (int i = 0; i < downloadUrls.size(); i++) {
                        try {
                            String FileName = insertTimeBeforeExtension(dowloadFileName.get(i), modifiedTime);
                            logger.info("文件名称 : {}", FileName);
                            String fileSavePath = dingTalkYiDa1_0impl.getDownloadUrl(accessToken, downloadUrls.get(i), this.system_token, this.user_id, this.app_type, dowloadFileName.get(i));
                            dingTalkStorageimpl.GetFileUploadInfoByDentryId(accessToken, FileSaveFolderId, fileSavePath, FileName);
                        } catch (Exception e) {
                            logger.error("下载和上传文件失败", e);
                        }
                    }
                    // 检查 Instance 是否已经存在
                    if (!instanceRepository.existsByInstanceIdAndModifiedTime(instanceId,modifiedTime)) {
                        Instance instanceEntity = new Instance();
                        instanceEntity.setInstanceId(instanceId);
                        instanceEntity.setJijinName(jijin_name);
                        instanceEntity.setJianchengName(jiancheng_name);
                        instanceEntity.setProjectName(xiangmu_name);
                        instanceEntity.setFolderList("/" + jijin_name + "/" + jiancheng_name + "/" + foldername);
                        instanceEntity.setInvested(true);
                        instanceEntity.setModifiedTime(modifiedTime);
                        instanceRepository.save(instanceEntity);
                    }

                    for (Object employee : new_employeeList) {
                        // 检查 Employee 是否已经存在
                        if (!employeeRepository.existsByJijinNameAndProjectNameAndEmployeeId(jijin_name, foldername, employee.toString())) {
                            Employee employeeEntity = new Employee();
                            employeeEntity.setJijinName(jijin_name);
                            employeeEntity.setProjectName(xiangmu_name);
                            employeeEntity.setJianchengName(jiancheng_name);
                            employeeEntity.setEmployeeId(employee.toString());
                            employeeEntity.setHasPermission(false); // 初始化为 false
                            employeeRepository.save(employeeEntity);
                        }
                    }

                } catch (Exception e) {
                    logger.error("处理实例失败", e);
                }
            }

            // 查询 has_permission 为 false 的员工
            List<Employee> employeesWithNoPermission = employeeRepository.findEmployeesWithNoPermission();
            // 调用赋予权限的方法
            grantPermissions(accessToken, employeesWithNoPermission, folderList);


        } catch (Exception e) {
            logger.error("处理表单失败 {}，表单ID: {}", e, chuzi_zhengming_form_id);
        }

    }

    private void grantPermissions(String accessToken, List<Employee> employeesWithNoPermission, Map<String, Map<String, String>> folderList) throws Exception {
        for (Employee employee : employeesWithNoPermission) {
            String jijin_name = employee.getJijinName();
            String xiangmu_name = employee.getProjectName();
            String folderPath = "/" + jijin_name + "/" + xiangmu_name;

            if (folderList.containsKey(folderPath)) {
                String uuid = folderList.get(folderPath).get("uuid");
                dingTalkStorageimpl.addPermission(accessToken, employee.getEmployeeId(), uuid);
                // 更新 has_permission 为 true
                employee.setHasPermission(true);
                employeeRepository.save(employee);
            } else {
                logger.error("Folder path " + folderPath + " not found in folderList for employee ID: " + employee.getEmployeeId());
            }
        }

    }

    private String insertTimeBeforeExtension(String fileName, String modifiedTime) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            // 如果没有找到扩展名，直接在文件名末尾添加 _time
            return fileName + "_" + modifiedTime;
        }
        String namePart = fileName.substring(0, lastDotIndex);
        String extensionPart = fileName.substring(lastDotIndex);
        return namePart + "_" + modifiedTime + extensionPart;
    }

}
